/**
 * 
 */
package qy.jalgotrade.stratanalyzer.returns;

import java.time.ZonedDateTime;
import java.util.Map;

import qy.jalgotrade.dataseries.SequenceDataSeries;
import qy.jalgotrade.event.EventHandler;
import qy.jalgotrade.stratanalyzer.StrategyAnalyzer;
import qy.jalgotrade.strategy.BaseStrategy;

/**
 * A :class:`pyalgotrade.stratanalyzer.StrategyAnalyzer` that calculates time-weighted returns for
 * the whole portfolio.
 * 
 * @author c-geo
 *
 */
public class Returns extends StrategyAnalyzer implements EventHandler {

	private SequenceDataSeries<Double> __netReturns;

	private SequenceDataSeries<Double> __cumReturns;

	/**
	 * @throws Exception
	 * 
	 */
	public Returns() throws Exception {

		this(0);
	}

	/**
	 * 
	 * @param maxLen
	 * @throws Exception
	 */
	public Returns(int maxLen) throws Exception {

		super();
		__netReturns = new SequenceDataSeries<>(maxLen);
		__cumReturns = new SequenceDataSeries<>(maxLen);
	}

	/**
	 * Returns a :class:`pyalgotrade.dataseries.DataSeries` with the returns for each bar.
	 * 
	 * @return
	 */
	public SequenceDataSeries<Double> getReturns() {

		return __netReturns;
	}

	/**
	 * Returns a :class:`pyalgotrade.dataseries.DataSeries` with the cumulative returns for each bar.
	 * 
	 * @return
	 */
	public SequenceDataSeries<Double> getCumulativeReturns() {

		return __cumReturns;
	}

	/* (non-Javadoc)
	 * @see qy.jalgotrade.event.EventHandler#handle(java.lang.String, java.util.Map)
	 */
	@Override
	public void handle(String eventName, Map<String, Object> params) throws Exception {

		ZonedDateTime dateTime = (ZonedDateTime) params.get("dateTime");
		ReturnsAnalyzerBase returnsAnalyzerBase = (ReturnsAnalyzerBase) params.get("returnsAnalyzerBase");
		__onReturns(dateTime, returnsAnalyzerBase);
	}

	private void __onReturns(ZonedDateTime dateTime, ReturnsAnalyzerBase returnsAnalyzerBase) throws Exception {

		__netReturns.appendWithDateTime(dateTime, returnsAnalyzerBase.getNetReturn());
		__cumReturns.appendWithDateTime(dateTime, returnsAnalyzerBase.getCumulativeReturn());
	}

	/*
	 * (non-Javadoc)
	 * @see qy.jalgotrade.stratanalyzer.StrategyAnalyzer#beforeAttach(qy.jalgotrade.strategy.BaseStrategy)
	 */
	@Override
	public void beforeAttach(BaseStrategy strat) throws Exception {

		// Get or create a shared ReturnsAnalyzerBase
		ReturnsAnalyzerBase analyzer = (ReturnsAnalyzerBase) ReturnsAnalyzerBase.getOrCreateShared(strat);
		analyzer.getEvent().subscribe(this);
	}
}
